<template>
  <div class="search-page">
    <!-- 顶部搜索区域 -->
    <div class="search-header">
      <div class="search-container">
        <!-- <router-link to="/" class="logo">
          <span>课</span>头条
        </router-link> -->
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="请输入要搜索的关键词"
            size="large"
            @keyup.enter="handleSearchInput"
          >
            <template #suffix>
              <el-icon @click="handleSearchInput">
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button
            type="primary"
            size="large"
            class="search-btn"
            @click="handleSearchInput"
          >
            搜索
          </el-button>
        </div>
        <div class="search-tips">
          <span>热搜：</span>
          <el-tag
            v-for="(tag, index) in hotTags"
            :key="index"
            class="hot-tag"
            effect="plain"
            @click="selectHotTag(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 搜索结果区域 -->
    <div class="search-results">
      <!-- 搜索信息 -->
      <div class="results-info">
        <h2>搜索"{{ searchQuery }}"的结果</h2>
        <div class="results-stats">
          <span class="total">找到 {{ totalResults }} 条相关新闻</span>
          <el-divider direction="vertical" />
          <span class="time">用时 {{ searchTime }} 秒</span>
          <el-divider direction="vertical" />
          <span class="page-info">第 {{ currentPage }} 页</span>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <!-- 无结果状态 -->
      <el-empty
        v-else-if="!loading && (!searchResults || searchResults.length === 0)"
        :image-size="200"
        :description="'第 ' + currentPage + ' 页没有找到相关新闻'"
      >
        <template #description>
          <p>{{ totalResults > 0 ? `第 ${currentPage} 页没有找到相关新闻` : '没有找到相关新闻' }}</p>
        </template>
        <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
      </el-empty>

      <!-- 搜索结果列表 -->
      <div v-else class="results-container">
        <div class="results-grid">
          <div
            v-for="(item, index) in searchResults"
            :key="item.id"
            class="result-card"
          >
            <router-link :to="'/news/' + item.id" class="card-link">
              <div class="card-image">
                <el-image
                  :src="item.imgUrl"
                  :alt="item.title"
                  fit="cover"
                  class="card-img"
                  :class="{'img-loaded': imageLoaded[index]}"
                  lazy
                  @load="imageLoaded[index] = true"
                  @error="handleImageError($event, item)"
                >
                  <template #placeholder>
                    <div class="image-placeholder">
                      <el-icon :size="40" color="#999"><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="card-content">
                <h3 class="card-title">{{ item.title }}</h3>
                <p class="card-summary">{{ item.summary }}</p>
                <div class="card-footer">
                  <div class="source">
                    <el-avatar :size="24" :src="item.authorAvatar" class="author-avatar">
                      <el-icon><User /></el-icon>
                    </el-avatar>
                    <span class="author-name">{{ item.author }}</span>
                  </div>
                  <div class="meta">
                    <span class="time">
                      <el-icon><Clock /></el-icon>
                      {{ item.time }}
                    </span>
                    <span class="comments">
                      <el-icon><ChatDotRound /></el-icon>
                      {{ item.comments }}评论
                    </span>
                  </div>
                </div>
              </div>
            </router-link>
<!--            <div class="card-actions">-->
<!--              <el-button text :icon="Share" class="action-btn">分享</el-button>-->
<!--              <el-button text :icon="WarnTriangleFilled" class="action-btn"><el-icon><WarnTriangleFilled /></el-icon>举报</el-button>-->
<!--              <el-button text :icon="Star" class="action-btn">收藏</el-button>-->
<!--              <el-button text :icon="ChatDotRound" class="action-btn">评论</el-button>-->
<!--            </div>-->
          </div>
        </div>

        <!-- 分页器 -->
        <div class="pagination-container" v-if="totalResults > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalResults"
            :page-sizes="[12, 24, 36, 48]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import {
  Search, Share, Star, ChatDotRound,
  Clock, User, Picture
} from '@element-plus/icons-vue'
import defaultImg from '@/assets/images/banner4.jpg'
import { ElMessage } from 'element-plus'

const route = useRoute()
const searchQuery = ref('')
const searchResults = ref([])
const loading = ref(false)
const totalResults = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const imageLoaded = ref({})
const searchTime = ref(0)
const sortType = ref('relevance')
const hotTags = ref(['科技前沿', '人工智能', '元宇宙', '电商运营', '编程开发', '视觉设计'])

// 计算当前页的数据
const paginatedResults = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return searchResults.value.slice(start, end)
})

const handlePageChange = async (page) => {
  console.log('Page changing to:', page, 'Current page:', currentPage.value)
  currentPage.value = page
  await handleSearch()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleImageError = (e, item) => {
  e.target.src = defaultImg
  // 更新数据中的图片地址
  const index = searchResults.value.findIndex(result => result.id === item.id)
  if (index !== -1) {
    searchResults.value[index].imgUrl = defaultImg
  }
}

const selectHotTag = (tag) => {
  searchQuery.value = tag
  handleSearch()
}

const changeSort = (type) => {
  console.log('Sort type changing to:', type)
  sortType.value = type
  currentPage.value = 1
  handleSearch(true)
}

const handleSearch = async (resetPage = false) => {
  if (!searchQuery.value.trim()) return

  const startTime = Date.now()
  loading.value = true
  imageLoaded.value = {}

  try {
    const params = {
      keyword: searchQuery.value,
      categoryId: '',
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      sortType: sortType.value
    }
    
    console.log('Sending search request with params:', params)

    const response = await axios.get('/app/news/searchNews', { params })

    if (response.data.code === 200 && response.data.data) {
      const { list, total, pageNum, pages } = response.data.data
      console.log('Search response:', response.data.data)

      // 更新总数
      totalResults.value = total || 0

      if (!list || list.length === 0) {
        ElMessage.warning(`第 ${currentPage.value} 页没有找到相关新闻`)
        searchResults.value = []
        return
      }

      // 更新搜索结果
      searchResults.value = list.map(news => ({
        id: news.id,
        title: news.title,
        imgUrl: news.picPath ? news.picPath : defaultImg,
        category: news.categoryName || '未分类',
        time: formatTime(news.createDate),
        comments: Math.floor(Math.random() * 100),
        summary: news.summary || '暂无摘要信息',
        author: news.author || '未知作者',
        authorAvatar: generateAvatarUrl(news.author),
        createDate: news.createDate
      }))

      console.log('Search results processed:', {
        total,
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        resultsCount: list.length,
        pages,
        results: searchResults.value
      })
    } else {
      ElMessage.error(response.data.message || '搜索失败')
      searchResults.value = []
      totalResults.value = 0
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
    searchResults.value = []
    totalResults.value = 0
  } finally {
    loading.value = false
    searchTime.value = ((Date.now() - startTime) / 1000).toFixed(2)
  }
}

const formatTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now - date

  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 生成随机头像URL
const generateAvatarUrl = (author) => {
  if (!author) return ''
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA502', '#9C89B8']
  const color = colors[Math.floor(Math.random() * colors.length)]
  return `https://ui-avatars.com/api/?name=${encodeURIComponent(author)}&background=${color.slice(1)}&color=fff`
}

// 搜索框输入处理
const handleSearchInput = async () => {
  currentPage.value = 1 // 重置到第一页
  await handleSearch()
}

// 监听路由变化
watch(() => route.query.q, (newVal) => {
  if (newVal) {
    searchQuery.value = newVal
    handleSearch(true)
  }
})

// 组件挂载时初始化
onMounted(() => {
  if (route.query.q) {
    searchQuery.value = route.query.q
    handleSearch(true)
  }
})

// 每页条数改变处理
const handleSizeChange = async (size) => {
  console.log('Page size changing to:', size)
  pageSize.value = size
  currentPage.value = 1
  await handleSearch()
}
</script>

<style scoped lang="scss">
.search-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.search-header {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 16px 0;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.logo {
  font-size: 28px;
  font-weight: 700;
  color: #ff4e4e;
  text-decoration: none;
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  span {
    background-color: #ff4e4e;
    color: white;
    border-radius: 4px;
    padding: 0 6px;
    margin-right: 4px;
  }
}

.search-box {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;

  :deep(.el-input) {
    flex: 1;

    .el-input__wrapper {
      border-radius: 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      padding: 0 20px;
      height: 48px;
    }

    .el-input__suffix {
      padding-right: 16px;
      cursor: pointer;

      .el-icon {
        font-size: 20px;
        color: #606266;
        transition: color 0.3s;

        &:hover {
          color: #ff4e4e;
        }
      }
    }
  }

  .search-btn {
    border-radius: 24px;
    padding: 0 30px;
    font-weight: 500;
    font-size: 16px;
    height: 48px;
    background-color: #ff4e4e;
    border: none;

    &:hover {
      background-color: #ff3333;
    }
  }
}

.search-tips {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;

  span {
    margin-right: 8px;
  }

  .hot-tag {
    margin-right: 10px;
    cursor: pointer;
    transition: all 0.3s;
    border-radius: 12px;
    padding: 2px 12px;

    &:hover {
      background-color: #ff4e4e;
      color: white;
    }
  }
}

.search-results {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.results-info {
  margin-bottom: 24px;

  h2 {
    font-size: 22px;
    font-weight: 600;
    color: #1a1a1a;
    margin-bottom: 12px;
  }
}

.results-stats {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;

  .total {
    font-weight: 500;
    color: #ff4e4e;
  }

  .time {
    color: #999;
  }

  .page-info {
    color: #666;
    font-weight: 500;
  }

  :deep(.el-divider) {
    height: 16px;
    margin: 0 12px;
  }
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.results-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

.result-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: #fff;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.06);
  border: 1px solid #eee;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
    border-color: #ff4e4e;

    .card-title {
      color: #ff4e4e;
    }
  }
}

.card-link {
  text-decoration: none;
  color: inherit;
  display: block;
}

.card-image {
  height: 160px;
  overflow: hidden;
  position: relative;

  .card-img {
    width: 100%;
    height: 100%;
    transition: transform 0.5s ease;

    &:hover {
      transform: scale(1.05);
    }
  }

  .image-placeholder {
    width: 100%;
    height: 100%;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.img-loaded {
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.card-content {
  padding: 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 48px;
}

.card-summary {
  font-size: 13px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 42px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.source {
  display: flex;
  align-items: center;

  .author-avatar {
    margin-right: 8px;
  }

  .author-name {
    font-weight: 500;
    color: #333;
  }
}

.meta {
  display: flex;
  gap: 12px;

  span {
    display: flex;
    align-items: center;

    .el-icon {
      margin-right: 4px;
      font-size: 12px;
    }
  }
}

.card-actions {
  display: flex;
  justify-content: space-around;
  padding: 12px 0;
  border-top: 1px solid #f5f5f5;

  .action-btn {
    font-size: 13px;
    color: #666;
    padding: 0 5px;

    &:hover {
      color: #ff4e4e;
    }

    .el-icon {
      margin-right: 4px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  margin-top: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  :deep(.el-pagination) {
    .el-pagination__total {
      margin-right: 16px;
    }

    .el-pagination__sizes {
      margin-right: 16px;
    }

    .btn-prev,
    .btn-next,
    .number {
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      margin: 0 4px;
      min-width: 32px;
      
      &:hover {
        color: #ff4e4e;
        border-color: #ff4e4e;
      }
    }

    .number.is-active {
      background-color: #ff4e4e;
      color: white;
      border-color: #ff4e4e;
    }
  }
}

@media (max-width: 768px) {
  .search-container {
    padding: 0 15px;
  }

  .logo {
    font-size: 24px;
    margin-bottom: 10px;
  }

  .search-box {
    flex-direction: column;
    gap: 10px;

    .search-btn {
      width: 100%;
    }
  }

  .results-grid {
    grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
    gap: 16px;
  }

  .skeleton-item {
    flex-direction: column;

    .skeleton-img {
      width: 100%;
      height: 180px;
      margin-right: 0;
      margin-bottom: 15px;
    }
  }
}
</style>
